#!/bin/python

import requests
import hashlib
import hmac
import base64
import urllib.parse
import argparse

# CloudStack API 端点和凭证
# host = "10.223.129.132"
# api_url = "http://" + host + ":8080/client/api"
# api_key = "Kbgsmvz3_GAxFd1AfHHMybhuIJsuRI0PooSZHY78Yg-5pB4th5Vf0EmF6oJQkYDDgaR2oNIbYW5ea_NiAjuWfA"
# secret_key = "tJu2pkri5E3z8W4EyjECJ1YY36xGgZJSOox8YnCgR6TK1x6ope3UiL5z21BUVhZZyS3IemA3G4L81uOEhaoYxg"


def generate_signature(params, secret_key):
    sorted_params = sorted(params.items())
    query_string = '&'.join(['='.join([k, urllib.parse.quote_plus(str(v))]) for k, v in sorted_params])
    signature = hmac.new(secret_key.encode('utf-8'), query_string.lower().encode('utf-8'), hashlib.sha1)
    signature = base64.b64encode(signature.digest())
    return signature.decode('utf-8')


def make_request(command, params):
    params['command'] = command
    params['apikey'] = api_key
    params['response'] = 'json'
    params['signature'] = generate_signature(params, secret_key)
    response = requests.get(api_url, params=params)
    return response.json()


if __name__ == '__main__':


    # 获取参数
    parser = argparse.ArgumentParser(
        description="Script to demonstrate command line argument parsing.",
        epilog="Example usage:\n"
               "\tpython script.py --host 10.223.129.132 --AK Kbgsmvz3_GA... --SK tJu2pkri5E3z...\n",
        formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument('--host', type=str, required=True, help='The acs management address')
    parser.add_argument('--AK', type=str, required=True, help='The ak of admin user in acs')
    parser.add_argument('--SK', type=str, required=True, help='The sk of admin user in acs')
    args = parser.parse_args()

    # 参数获取
    host = args.host
    api_url = "http://" + host + ":8080/client/api"
    api_key = args.AK
    secret_key = args.SK

    # 要修改的全局参数列表
    global_parameters = {
        "host": host,
        "enable.storage.migration": "disable",
        "snapshot.backup.to.secondary": "disable",
        "secstorage.allowed.internal.sites": "10.0.0.0/8,172.16.0.0/12,192.168.0.0/16",
        "ha.tag": "HCMHA",
        "storage.template.cleanup.enabled": "disable",
        "vm.serviceoffering.cpu.cores.max": "100",
        "max.account.cpus": "-1",
        "max.project.cpus": "-1",
        "cpu.overprovisioning.factor": "4",
        "max.account.memory": "-1",
        "max.domain.memory": "-1",
        "max.project.memory": "-1",
        "custom.diskoffering.size.max": "40960",
        "network.throttling.rate": "5000",
        "vm.network.throttling.rate": "5000",
        "kvm.snapshot.enabled": "enable",
        "kvm.vmstoragesnapshot": "enabled",
        "max.account.snapshots": "-1",
        "max.project.snapshots": "-1",
        "storage.max.volume.size": "40960",
        "capacity.skipcounting.hours": "60",
        "vm.stats.interval": "300000",
        "vm.stats.max.retention.time": "60",
        "allow.public.user.templates": "disable",
        "system.vm.public.ip.reservation.mode.strictness": "enable",
        "share.public.templates.with.other.domains": "enable"

    }

    # 遍历全局参数列表
    for param, value in global_parameters.items():
        params = {
            "name": param,
            "value": value
        }
        response = make_request("updateConfiguration", params)
        if "updateconfigurationresponse" in response:
            print(f"Successfully updated {param} to {value}")
        else:
            print(f"Failed to update {param}: {response}")

    print("All parameters updated successfully.")
